package com.example.zzx.dovebook.personalcenter

import android.os.Bundle
import android.view.MenuItem
import androidx.lifecycle.Observer
import com.example.baselibrary.commonutil.FormatUtil
import com.example.baselibrary.commonutil.Logger
import com.example.baselibrary.image.GlideManager
import com.example.dovebookui.widget.IndicatorAdapter
import com.example.zzx.dovebook.R
import com.example.zzx.dovebook.base.BaseActivity
import com.example.zzx.dovebook.base.BaseFragment
import com.example.zzx.dovebook.base.CommonRepository
import com.example.zzx.dovebook.base.CommonViewModel
import com.example.zzx.dovebook.base.ValueWrapper.TYPE_NORMAL
import com.example.zzx.dovebook.base.extensions.startFollowerActivity
import com.example.zzx.dovebook.base.extensions.startFollowingActivity
import com.example.zzx.dovebook.personalcenter.pass.PassFragment
import com.example.zzx.dovebook.personalcenter.receive.ReceiveFragment
import com.example.zzx.dovebook.personalcenter.share.ShareFragment
import com.example.zzx.dovebook.user.model.UserInfo
import com.example.zzx.dovebook.widget.AppBarOverScrollBehavior
import kotlinx.android.synthetic.main.activity_user_detail.*
import net.lucode.hackware.magicindicator.ViewPagerHelper
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator

class UserDetailActivity: BaseActivity<CommonViewModel<CommonRepository>>() {

    override fun getLayoutId(): Int = R.layout.activity_user_detail

    private var userId: String? = null

    private var userName: String? = null

    private lateinit var commonNavigator: CommonNavigator

    private val titleList = listOf("分享", "传递", "接收")

    private val fragmentList = listOf<BaseFragment<*>>(
        ShareFragment(),
        PassFragment(),
        ReceiveFragment()
    )

    private lateinit var fragmentAdapter: FragmentAdapter

    override fun createViewModel(): Class<CommonViewModel<CommonRepository>> =
        CommonViewModel::class.java as Class<CommonViewModel<CommonRepository>>

    override fun createRepository(): Any = CommonRepository()

    override fun initViews(savedInstanceState: Bundle?) {

        bgImage.tag = AppBarOverScrollBehavior.targetViewTag

        setupToolbar()

        setupViewPager()
    }

    /**
     * 绑定其它一些View， 这些View需要再查询用户信息完成之后才能绑定
     */
    private fun bindActionViews(userInfo: UserInfo) {
        followerCountTv.text = "粉丝${FormatUtil.countFormat(userInfo.followerCount)}"
        followingCountTv.text = "关注${FormatUtil.countFormat(userInfo.followingCount)}"
        followingCountTv.setOnClickListener {
            startFollowingActivity(userInfo.userId, userInfo.userName)
        }

        followerCountTv.setOnClickListener {
            startFollowerActivity(userInfo.userId, userInfo.userName)
        }
    }

    override fun initIntent(savedInstanceState: Bundle?) {
        userId = intent.getStringExtra(getString(R.string.user_id_arg_name))
        userName = intent.getStringExtra(getString(R.string.user_name_arg_name)) ?: ""
        if (userId == null) {
            Logger.e(TAG, "initIntent -> userId is null, finish $TAG")
            finish()
        }
    }

    private fun setupToolbar() {
        setSupportActionBar(toolbar)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        supportActionBar?.title = userName
    }

    private fun setupViewPager() {
        fragmentAdapter = FragmentAdapter(supportFragmentManager, fragmentList, titleList.toTypedArray())
        commonNavigator = CommonNavigator(this).apply {
            adapter = IndicatorAdapter().apply {
                titleList = this@UserDetailActivity.titleList
                onItemClickListener = { index ->
                    viewPager.currentItem = index
                }
            }
            isAdjustMode = true
        }
        indicator.navigator = commonNavigator
        ViewPagerHelper.bind(indicator, viewPager)
        viewPager.adapter = fragmentAdapter
    }

    override fun initOptions(savedInstanceState: Bundle?) {
        viewModel.getUserInfo(userId!!).observe(this, Observer {
            if (it.type == TYPE_NORMAL) {
                (it.value as UserInfo).apply {
                    bindActionViews(this)
                    showUserAvatar(userAvatarPath)
                }
            }
        })
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            android.R.id.home -> finish()
        }
        return super.onOptionsItemSelected(item)
    }

    /**
     * 展示用户头像和背景图片，背景图片为用户头像的高斯模糊
     * [userAvatarPath] 用户头像的地址
     */
    private fun showUserAvatar(userAvatarPath: String?) {
        //在调用Glide之前将[bgImg]的Tag设置为null,以免Glide抛出异常
        bgImage.tag = null
        userAvatarPath?.apply {
            GlideManager.loadImage(this@UserDetailActivity, this, userAvatarImage)
            GlideManager.loadImageBlur(this@UserDetailActivity, this, bgImage)
            return
        }
        GlideManager.loadImage(this@UserDetailActivity, R.drawable.default_avatar, userAvatarImage)
        GlideManager.loadImageBlur(this, R.drawable.default_avatar, bgImage)
    }
}